package org.orbis.logging;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class BinaryBufferingLog{
	protected FileOutputStream inputStream;
	protected FileInputStream reliefStream;
	protected boolean isReliefMode;
	private File logFile;

	public BinaryBufferingLog(String directory, String logFile) throws IOException{
		this.logFile = new File(new StringBuffer(directory).append("/").append(logFile).toString());

		if(!this.logFile.exists()){
			// File not exists -> Normal logging mode
			this.logFile.createNewFile();
			this.inputStream = new FileOutputStream(this.logFile);
		}else{
			// File exists -> Relief mode
			this.reliefStream = new FileInputStream(this.logFile);
			this.isReliefMode = true;
		}
	}

	public boolean isReliefMode(){
		return isReliefMode;
	}

	public boolean isEndToRead() throws IOException{
		if(!isReliefMode) return true;
		return reliefStream.available() == 0;
	}
	
	public void terminate() throws IOException {
		if(reliefStream != null) reliefStream.close();
		if(inputStream != null) inputStream.close();
		logFile.delete();
	}

	// Close relief stream, delete log file and recreate it
	public void endRelief() throws IOException{
		if(!isReliefMode) return;
		if(reliefStream != null) reliefStream.close();

		logFile.delete();
		logFile.createNewFile();

		inputStream = new FileOutputStream(logFile);
		isReliefMode = false;
	}

	// Read less than 1024 byte or until buffer gets 0x00
	public byte[] relief() throws IOException{
		if(!isReliefMode) return null;
		int maxCount = 1024;
		byte[] b = new byte[maxCount];
		int count;
		for(count = 0; count < maxCount; count++){
			b[count] = (byte)reliefStream.read();
			if(b[count] == 0x00) break;
		}

		return count == 1024? b: Arrays.copyOf(b, count);
	}

	public void log(byte[] b) throws IOException{
		if(isReliefMode) return;

		inputStream.write(b);
	}
}
